//
//  OAReceiveDetailViewController.m
//  LongOA
//
//  Created by XuJiuming on 15/9/19.
//  Copyright (c) 2015年 梁文朗. All rights reserved.
//

#import "OAReceiveDetailViewController.h"
#import "GetMailContentRequest.h"
#import "GetMailContentRespones.h"
#import "GetMailDealStatusRequest.h"
#import "GetMailDealStatusResponse.h"
#import "RCLabel.h"
#import "HtmlString.h"
#import "DealMailRequest.h"
#import "DealMailResponse.h"
#import "SetMailReadFlagRequest.h"
#import "SetMailReadFlagResponse.h"
#import "GetFileRequest.h"
#import "GetFileResponse.h"
#import "PhotoBroswerVC.h"
#import "OAWebShowViewController.h"
//#import "OASendDetailViewController.h"
#import "OANewEmailViewController.h"

#define ATTHEIGHT   150.0f;

@interface OAReceiveDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIView *view8;
    NSString* s_msg;
    NSArray* arrAtt;
    UITableView* mailTableView;
    UIButton *btnOk;
    int icount;
}
@property (nonatomic,strong) NSMutableArray* arrNameList;   //真名和串名
@property (nonatomic,strong) NSString* attFileName;
@property (nonatomic) int attCurrent;
@property (nonatomic) NSIndexPath *indexPathCurrent;
@property (nonatomic) int fileID;
@end

@implementation OAReceiveDetailViewController
@synthesize arrList;
@synthesize iindex;

- (void)leftBarClicked:(id)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}
//回复
- (void)rightBarClicked:(id)sender {
    OANewEmailViewController* vc=[[OANewEmailViewController alloc] init];
    //[self.navigationController pushViewController:vc animated:NO];
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    vc.strReply=[dict objectForKey:@"sendemp"];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    icount=0;
    [self createNavWithTitleSub:@"内部邮件" subtitle:@"收件箱" createMenuItem:^UIView *(int nIndex)
     {
         float btnwidth=40.0f;
         float btnheight=40.0f;
         if (nIndex ==0)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(leftBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
             return btn;
         }
         
         if (nIndex ==2)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(self.navView.width - btnwidth - 10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"ic_reply"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(rightBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             
             return btn;
         }
         
         return nil;
     }];
    btnOk = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnOk setFrame:CGRectMake(self.navView.width - 50.0-40.0, 20.0f+(self.navView.height-20 - 40)/2, 30.0, 40.0)];
    [btnOk setTitle:@"未确认" forState:UIControlStateNormal];
    btnOk.titleLabel.font=[UIFont systemFontOfSize:10.0];
    [btnOk addTarget:self action:@selector(confirmBarClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnOk];
    
    view8=[[UIView alloc] initWithFrame:CGRectMake(-1.0, SCREEN_HEIGHT-33.0, SCREEN_WIDTH+2.0, 33.0)];
    view8.layer.borderColor=[UIColor darkTextColor].CGColor;
    view8.layer.borderWidth=1.0f;
    [self.view addSubview:view8];
    
    float fvWidth=35.0;
    float fvHeight=29.0;
    UIButton *customButton1 = [[UIButton alloc] initWithFrame:CGRectMake(70.0, 2, fvWidth, fvHeight)];
    [customButton1 addTarget:self action:@selector(leftBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [customButton1 setImage:[UIImage imageNamed:@"ic_up_normal"] forState:UIControlStateNormal];
    [view8 addSubview:customButton1];
    UIButton *customButton2 = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-70.0f-fvWidth, 2, fvWidth, fvHeight)];
    [customButton2 addTarget:self action:@selector(rightBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [customButton2 setImage:[UIImage imageNamed:@"ic_down_normal"] forState:UIControlStateNormal];
    [view8 addSubview:customButton2];
    
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    int imsgid=[[dict objectForKey:@"msgid"] intValue];
    
    
    mailTableView=[[UITableView alloc]initWithFrame:CGRectMake(0.0f, self.navView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT-self.navView.bottom-1.0) style:UITableViewStylePlain];
    mailTableView.delegate=self;
    mailTableView.dataSource=self;
    mailTableView.backgroundColor=[UIColor clearColor];
    mailTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:mailTableView];
    [self setExtraCellLineHidden:mailTableView];
    
    _arrNameList=[[NSMutableArray alloc] init];
    [self getEmailContent:imsgid];
    
    [self readFlag];
}
- (void)readFlag {
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    
    SetMailReadFlagRequest * request = [[SetMailReadFlagRequest alloc] init];
    request.token = token;
    request.msgids=@[[dict objectForKey:@"msgid"]];
    
    request.read_flag=1;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[SetMailReadFlagResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    SetMailReadFlagResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
        [self showAlertWithContent:rslt.ErrMsg];
    }
    else{
        [mailTableView reloadData];
        
        //[btnOk setTitle:@"未确认" forState:UIControlStateNormal];
    }
}];
}
-(void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}
//确认
- (void)confirmBarClicked:(id)sender {
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    
    DealMailRequest * request = [[DealMailRequest alloc] init];
    request.token = token;
    request.msgids=@[[dict objectForKey:@"msgid"]];
    
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[DealMailResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    DealMailResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
        [self showAlertWithContent:rslt.ErrMsg];
    }
    else{
        [btnOk setTitle:@"已确认" forState:UIControlStateNormal];
        btnOk.enabled=NO;
        
        //[btnOk setTitle:@"未确认" forState:UIControlStateNormal];
    }
}];
}
#pragma mark bottom bar
- (void)leftBtnPressed:(id)sender {
    if (iindex>0) {
        iindex--;
    } else {
        return;
    }
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    int imsgid=[[dict objectForKey:@"msgid"] intValue];
    [self getEmailContent:imsgid];
}

- (void)rightBtnPressed:(id)sender {
    if (iindex<[arrList count]-1) {
        iindex++;
    } else {
        return;
    }
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    int imsgid=[[dict objectForKey:@"msgid"] intValue];
    [self getEmailContent:imsgid];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark getMailContent
- (void)getEmailContent:(int)msgid1 {
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    
    GetMailContentRequest * request = [[GetMailContentRequest alloc] init];
    request.token = token;
    request.msgid=msgid1;
    request.ignore=0;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[GetMailContentRespones class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    GetMailContentRespones* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
    }
    else{
        //NSLog(@"==%@",rslt.s_msg);
        s_msg=rslt.s_msg;
        arrAtt=rslt.list;
        //NSLog(@"arr=%@--%i",rslt.list,msgid1);
        [mailTableView reloadData];
  
        //[self performSelector:@selector(showAtt) withObject:nil afterDelay:0.1];
        
        
        /*
        if (arrList.count>0) { // && lastid!=0
            NSArray *myarray= rslt.list;
            int ii=(int)[myarray count];
            
            if (ii>0) {
                NSMutableArray *array=[[NSMutableArray alloc]init];
                [array addObjectsFromArray:arrList];
                [array addObjectsFromArray:myarray];
                
                arrList=array;
            }
        } else {
            arrList=rslt.list;
        }
        NSLog(@"%@",arrList);
        [mailTableView reloadData];
         */
    }
}];
}
- (void)showAtt {
    if (arrAtt.count>0) {
        for (int i=0; i<[arrAtt count]; i++) {
            NSDictionary* dict=[arrAtt objectAtIndex:i];
            int fileId=[[dict objectForKey:@"fileID"] intValue];
            [self getAttach:fileId withFinish:i+1];
        }
    }
}
- (void)getAttach:(int)fileID withFinish:(int)ii {
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    
    GetFileRequest * request = [[GetFileRequest alloc] init];
    request.token = token;
    request.id=fileID;
    request.type=@"MailAnnex";
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[GetFileResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    GetFileResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
    }
    else{
        //NSLog(@"==%@--%@",rslt.filename,rslt.data);
        NSString* temp = [rslt.data stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
        NSDictionary* dict= [NSDictionary dictionaryWithObjectsAndKeys:rslt.filename,@"Name",temp,@"Data", nil];
        
        [_arrNameList addObject:dict];
        if ([arrAtt count]==ii) {
            if ([[_attFileName pathExtension] isEqualToString:@"doc"] || [[_attFileName pathExtension] isEqualToString:@"pdf"] || [[_attFileName pathExtension] isEqualToString:@"xls"]) {
                NSDictionary* dict1=[_arrNameList objectAtIndex:_attCurrent];
                NSString* fileAddress=nil;
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                NSString *path = [paths objectAtIndex:0];
                fileAddress=[path stringByAppendingPathComponent:[dict1 objectForKey:@"Data"]];
                
                NSString *tmpDir = NSTemporaryDirectory();
                //tmpDir=[[tmpDir stringByAppendingPathComponent:@"temp"] stringByAppendingPathExtension:fileExt];
                tmpDir=[[tmpDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%i",_fileID]] stringByAppendingPathExtension:[_attFileName pathExtension]];
                
                NSError *error;
                NSFileManager *fileMgr = [NSFileManager defaultManager];
                //BOOL isDir;
//                if ([fileMgr fileExistsAtPath:tmpDir isDirectory:&isDir]) {
//                    [fileMgr removeItemAtPath:tmpDir error:&error];
//                }
                
                if ([fileMgr copyItemAtPath:fileAddress toPath:tmpDir error:&error] != YES)
                    NSLog(@"Unable to move file: %@", [error localizedDescription]);
                
                
                
                
                OAWebShowViewController* vc=[[OAWebShowViewController alloc] init];
                //[self.navigationController pushViewController:vc animated:NO];
                vc.myTitle=[_attFileName stringByDeletingPathExtension];
                //NSDictionary* dict1=[_arrNameList objectAtIndex:_attCurrent];
                //NSLog(@"==%@",dict1);
                vc.fileName=tmpDir; //[dict1 objectForKey:@"Data"];
                vc.fileExt=[_attFileName pathExtension];
                vc.fileRealName=_attFileName;
                vc.fileID=_fileID;
                [self presentViewController:vc animated:NO completion:nil];
            } else {
                UIImageView *imgView=(UIImageView *)[[mailTableView cellForRowAtIndexPath:_indexPathCurrent] viewWithTag:301];
                [self localImageShow:_attCurrent withImgView:imgView withArr:_arrNameList];
            }
        }
    }
}];
}
#pragma mark TableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrAtt count]+2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 60.0;
    } else if (indexPath.row==1) {
        return ATTHEIGHT;
    }
    return 33.0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//        cell.backgroundColor=COLOR_BACK;
//        cell.contentView.backgroundColor=COLOR_BACK;
        UILabel* lab1=[[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0, 200.0, 20.0)];
        lab1.backgroundColor=[UIColor clearColor];
        lab1.tag=11;
        lab1.textColor=[UIColor darkTextColor];
        lab1.font=[UIFont systemFontOfSize:13.0f];
        [cell.contentView addSubview:lab1];
        
        UILabel* lab2=[[UILabel alloc] initWithFrame:CGRectMake(5.0, lab1.bottom, 200.0, 20.0)];
        lab2.backgroundColor=[UIColor clearColor];
        lab2.tag=12;
        lab2.textColor=[UIColor lightGrayColor];
        lab2.font=[UIFont systemFontOfSize:11.0f];
        lab2.text=@"   发件人:";
        [cell.contentView addSubview:lab2];
        UILabel* lab3=[[UILabel alloc] initWithFrame:CGRectMake(5.0, lab2.bottom, 200.0, 17.0)];
        lab3.backgroundColor=[UIColor clearColor];
        lab3.tag=13;
        lab3.textColor=[UIColor lightGrayColor];
        lab3.font=[UIFont systemFontOfSize:11.0f];
        lab3.text=@"发件时间:";
        [cell.contentView addSubview:lab3];
        
        UISwitch* swith=[[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-51.0-40.0, (60.0-31.0)/2, 51.0, 31.0)];
        [swith addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        swith.tag=201;
        swith.on=YES;
        [cell.contentView addSubview:swith];
        UILabel* lab4=[[UILabel alloc] initWithFrame:CGRectMake(swith.right+2.0, 0.0, 30.0, 60.0)];
        lab4.backgroundColor=[UIColor clearColor];
        lab4.tag=14;
        lab4.textColor=[UIColor lightGrayColor];
        lab4.font=[UIFont systemFontOfSize:13.0f];
        lab4.text=@"已读";
        [cell.contentView addSubview:lab4];
        
//        RCLabel *tempLabel = [[RCLabel alloc] initWithFrame:CGRectMake(5,0,SCREEN_WIDTH-10.0,135)];
//        tempLabel.tag=991;
//        [cell.contentView addSubview:tempLabel];
        UIWebView* webview=[[UIWebView alloc] initWithFrame:CGRectMake(5.0,0, SCREEN_WIDTH-10.0, 135.0)];
        webview.tag=991;
        webview.scrollView.bounces=NO;
        webview.scrollView.contentSize=CGSizeMake(SCREEN_WIDTH-10.0,135.0);
        [cell.contentView addSubview:webview];
        
        UIView* vi=[[UIView alloc] initWithFrame:CGRectMake(0.0, 49.5, SCREEN_WIDTH, 0.5)];
        vi.backgroundColor=[UIColor groupTableViewBackgroundColor];
        vi.tag=101;
        [cell.contentView addSubview:vi];
        UILabel* lab5=[[UILabel alloc] initWithFrame:CGRectMake(15.0, 150.0 - 13.5, 30.0, 13.0)];
        lab5.backgroundColor=[UIColor whiteColor];
        lab5.tag=15;
        lab5.textColor=[UIColor lightGrayColor];
        lab5.font=[UIFont systemFontOfSize:13.0f];
        lab5.text=@"附件";
        lab5.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:lab5];
        
        UIImageView* imgico=[[UIImageView alloc] initWithFrame:CGRectMake(5.0, 2.0, 29.0, 29.0)];
        imgico.tag=301;
        [cell.contentView addSubview:imgico];
        UILabel* lab6=[[UILabel alloc] initWithFrame:CGRectMake(imgico.right+2.0, 2.0, 200.0, 15.0)];
        lab6.backgroundColor=[UIColor whiteColor];
        lab6.tag=16;
        lab6.textColor=[UIColor lightGrayColor];
        lab6.font=[UIFont systemFontOfSize:11.0f];
        //lab6.text=@"";
        //lab6.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:lab6];
        UILabel* lab7=[[UILabel alloc] initWithFrame:CGRectMake(imgico.right+2.0, lab6.bottom, 200.0, 15.0)];
        lab7.backgroundColor=[UIColor whiteColor];
        lab7.tag=17;
        lab7.textColor=[UIColor lightGrayColor];
        lab7.font=[UIFont systemFontOfSize:11.0f];
        //lab7.text=@"";
        //lab7.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:lab7];
        
        UIImageView* imgico1=[[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-25.0, (33.0-13.0)/2, 13.0, 13.0)];
        imgico1.tag=401;
        imgico1.image=[UIImage imageNamed:@"icon39"];
        [cell.contentView addSubview:imgico1];
    }
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    NSLog(@"%@",dict);
    UILabel* lab1=(UILabel*)[cell viewWithTag:11];
    UILabel* lab2=(UILabel*)[cell viewWithTag:12];
    UILabel* lab3=(UILabel*)[cell viewWithTag:13];
    UILabel* lab4=(UILabel*)[cell viewWithTag:14];
    UILabel* lab5=(UILabel*)[cell viewWithTag:15];
    UILabel* lab6=(UILabel*)[cell viewWithTag:16];
    UILabel* lab7=(UILabel*)[cell viewWithTag:17];
    UIView* vi1=(UIView *)[cell viewWithTag:101];
    UISwitch* swith=(UISwitch*)[cell viewWithTag:201];
    UIImageView* imgico=(UIImageView*)[cell viewWithTag:301];
    UIImageView* imgico1=(UIImageView*)[cell viewWithTag:401];
    
//    RCLabel *tempLabel = (RCLabel *)[cell viewWithTag:991];
    UIWebView* webview = (UIWebView *)[cell viewWithTag:991];
    
    if (indexPath.row==0) {
        imgico.hidden=YES;
        imgico1.hidden=YES;
        lab6.hidden=YES;
        lab7.hidden=YES;
        //tempLabel.hidden=YES;
        webview.hidden=YES;
        lab1.text=[dict objectForKey:@"title"];
        lab1.hidden=NO;
        
        int itag=[[dict objectForKey:@"dealFlag"] intValue];
        //NSString* dealFlag=@"[未确认]";
        if (itag==1) {
            [btnOk setTitle:@"已确认" forState:UIControlStateNormal];
            btnOk.enabled=NO;
        } else {
            [btnOk setTitle:@"未确认" forState:UIControlStateNormal];
            btnOk.enabled=YES;
        }
        lab2.hidden=NO;
        lab2.text=[NSString stringWithFormat:@"   发件人:%@",[dict objectForKey:@"sendemp"]];
        
        lab3.hidden=NO;
        lab3.text=[NSString stringWithFormat:@"发件时间:%@",[dict objectForKey:@"senddt"]];

        vi1.frame=CGRectMake(0.0, 59.5, SCREEN_WIDTH, 0.5);
        if (icount==0) {
            lab4.text=@"已读";
            
            NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
            int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
            NSDictionary* dict1=[arrList objectAtIndex:iindex];
            
            SetMailReadFlagRequest * request = [[SetMailReadFlagRequest alloc] init];
            request.token = token;
            request.msgids=@[[dict1 objectForKey:@"msgid"]];
            request.read_flag=1;
            
            id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
            [clinet Doexecute:request
                     RspClass:[SetMailReadFlagResponse class]
                       andMsg:@"获取信息..."
                      andView:self.view
 globalTimelinePostsWithBlock:^(id rsp) {
     //SetMailReadFlagResponse* rslt = rsp;
     
 }];
        } else {
            if (icount==1) {
                lab4.text=@"已读";
            } else {
                lab4.text=@"未读";
            }
        }
//        else {
//            int iread=[[dict objectForKey:@"read_flag"] intValue];
//            if (iread==1) {
//                lab4.text=@"已读";
//                swith.on=NO;
//            } else {
//                lab4.text=@"未读";
//                swith.on=YES;
//            }
//        }
        
        swith.hidden=NO;
        lab4.hidden=NO;
        lab5.hidden=YES;
    } else {
        lab1.hidden=YES;
        lab2.hidden=YES;
        lab3.hidden=YES;
        lab4.hidden=YES;
        swith.hidden=YES;
        if (indexPath.row==1) {
            vi1.frame=CGRectMake(0.0, 150.0-13.5/2, SCREEN_WIDTH, 0.5);
            lab5.hidden=NO;
            imgico.hidden=YES;
            lab6.hidden=YES;
            lab7.hidden=YES;
            imgico1.hidden=YES;
            //tempLabel.hidden=NO;
            webview.hidden=NO;
            if (s_msg.length>0) {
//                NSString *transformStr = [HtmlString transformString:s_msg];
                //RCLabelComponentsStructure *componentsDS = [RCLabel extractTextStyle:transformStr];
//                RTLabelComponentsStructure *componentsDS = [RCLabel extractTextStyle:transformStr];
//                tempLabel.componentsAndPlainText = componentsDS;
                [self loadContent:s_msg withWeb:webview];
            }
            
        } else {
            //tempLabel.hidden=YES;
            webview.hidden=YES;
            imgico1.hidden=NO;
            NSDictionary* dict1=[arrAtt objectAtIndex:indexPath.row-2];
            lab6.text=[dict1 objectForKey:@"fileName"];
            lab7.text=[dict1 objectForKey:@"fileSize"];
            NSRange rangedoc = [[dict1 objectForKey:@"fileName"] rangeOfString:@".doc"];
            if (rangedoc.length>0)
                imgico.image=[UIImage imageNamed:@"filetype_word_h32"];
            else
                imgico.image=[UIImage imageNamed:@"image_default_bg"];
            lab5.hidden=YES;
            imgico.hidden=NO;
            lab6.hidden=NO;
            lab7.hidden=NO;
            vi1.frame=CGRectMake(0.0, 32.5, SCREEN_WIDTH, 0.5);
        }
    }

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row<2) {
        return;
    }
    
    
    NSDictionary* dict=[arrAtt objectAtIndex:indexPath.row-2];
    _attFileName=[dict objectForKey:@"fileName"];
    _attCurrent=(int)indexPath.row-2;
    _indexPathCurrent=indexPath;
    //NSLog(@"-%@-",dict);
    _fileID=[[NSString stringWithFormat:@"%@%@",[dict objectForKey:@"fileID"],[dict objectForKey:@"msgid"]] intValue];
    //NSLog(<#NSString * _Nonnull format, ...#>)
    
    NSString *tmpDir = NSTemporaryDirectory();
    //tmpDir=[[tmpDir stringByAppendingPathComponent:@"temp"] stringByAppendingPathExtension:fileExt];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
//    if ([fileMgr fileExistsAtPath:tmpDir]) {
        if ([[_attFileName pathExtension] isEqualToString:@"doc"] || [[_attFileName pathExtension] isEqualToString:@"pdf"] || [[_attFileName pathExtension] isEqualToString:@"xls"]) {
            
            tmpDir=[[tmpDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%i",_fileID]] stringByAppendingPathExtension:[_attFileName pathExtension]];
            
            if ([fileMgr fileExistsAtPath:tmpDir]) {
                OAWebShowViewController* vc=[[OAWebShowViewController alloc] init];
                //[self.navigationController pushViewController:vc animated:NO];
                vc.myTitle=[_attFileName stringByDeletingPathExtension];
                //NSDictionary* dict1=[_arrNameList objectAtIndex:_attCurrent];
                //NSLog(@"==%@",dict1);
                //vc.fileName=[dict1 objectForKey:@"Data"];
                vc.fileName=tmpDir;
                vc.fileExt=[_attFileName pathExtension];
                vc.fileRealName=_attFileName;
                vc.fileID=_fileID;
                [self presentViewController:vc animated:NO completion:nil];
            } else {
                [self showAtt];
            }
        } else {
            tmpDir=[tmpDir stringByAppendingPathComponent:_attFileName];
            //NSLog(@"-)
            if ([fileMgr fileExistsAtPath:tmpDir]) {
                UIImageView *imgView=(UIImageView *)[[mailTableView cellForRowAtIndexPath:_indexPathCurrent] viewWithTag:301];
                [self localImageShow:_attCurrent withImgView:imgView withArr:_arrNameList];
            } else {
                [self showAtt];
            }
        }
    
    
    
    
    //NSLog(@"--%@",_attFileName);
//    NSString* fileName=[dict objectForKey:@"fileName"];
//    if ([[fileName pathExtension] isEqualToString:@"doc"] || [[fileName pathExtension] isEqualToString:@"pdf"] || [[fileName pathExtension] isEqualToString:@"xls"]) {
//        OAWebShowViewController* vc=[[OAWebShowViewController alloc] init];
//        //[self.navigationController pushViewController:vc animated:NO];
//        vc.myTitle=[fileName stringByDeletingPathExtension];
//        NSDictionary* dict1=[_arrNameList objectAtIndex:indexPath.row-2];
//        vc.fileName=[dict1 objectForKey:@"Data"];
//        vc.fileExt=[fileName pathExtension];
//        [self presentViewController:vc animated:NO completion:nil];
//    } else {
//        UIImageView *imgView=(UIImageView *)[[mailTableView cellForRowAtIndexPath:indexPath] viewWithTag:301];
//        [self localImageShow:indexPath.row-2 withImgView:imgView withArr:_arrNameList];
//    }
    /*
     {
     fileID = 34;
     fileName = "\U63a5\U53e3\U8bf4\U660e.doc";
     fileSize = "204.50K";
     filetype = 0;
     msgid = 55;
     }
     */
}
/*
 *  本地图片展示
 */
-(void)localImageShow:(NSUInteger)index withImgView:(UIImageView *)imgView withArr:(NSArray*)imageArray {
    //__weak typeof(self) weakSelf=self;
    NSMutableArray *arr= [[NSMutableArray alloc] init];
    //NSLog(@"%lu---%@",index,_arrNameList);
    for (int i=0; i<[imageArray count]; i++) {
        NSDictionary* dict=[imageArray objectAtIndex:i];
        NSString* fileName=[dict objectForKey:@"Name"];
        NSRange range1 = [fileName rangeOfString:@".doc"];
        NSRange range2 = [fileName rangeOfString:@".xls"];
        NSRange range3 = [fileName rangeOfString:@".pdf"];
        if (range1.length >0 || range2.length>0 || range3.length>0) {
            if (i<index) {
                index -=1;
            }
        } else {
            NSString* fileAddress=nil;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *path = [paths objectAtIndex:0];
            //NSDictionary* dict1=[_arrNameList objectAtIndex:i];
            fileAddress=[path stringByAppendingPathComponent:[dict objectForKey:@"Data"]];

            NSString *tmpDir = NSTemporaryDirectory();
            tmpDir=[tmpDir stringByAppendingPathComponent:fileName];
            
            NSError *error;
            NSFileManager *fileMgr = [NSFileManager defaultManager];
            BOOL isDir;
            if ([fileMgr fileExistsAtPath:tmpDir isDirectory:&isDir]) {
                [fileMgr removeItemAtPath:tmpDir error:&error];
            }
            if ([fileMgr moveItemAtPath:fileAddress toPath:tmpDir error:&error] != YES)
                NSLog(@"Unable to move file: %@", [error localizedDescription]);
            //NSLog(@"%@-%@-%@",tmpDir,fileAddress,fileName);
            [arr addObject:tmpDir];
        }
    }
    //NSLog(@"%@",arr);
    [PhotoBroswerVC show:self type:PhotoBroswerVCTypeZoom index:index photoModelBlock:^NSArray *{
        //NSArray *localImages = weakSelf.images;
        //NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:self.itemArray.count];
        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:arr.count];
        for (NSUInteger i = 0; i< arr.count; i++) {
            PhotoModel *pbModel=[[PhotoModel alloc] init];
            pbModel.mid = i + 1;
            pbModel.title = nil; //[NSString stringWithFormat:@"标题%@",@(i+1)];
            pbModel.desc = nil; //[NSString stringWithFormat:@"描述文字%@",@(i+1)];
            //pbModel.image = localImages[i];
            //NSLog(@"%@",[self.itemArray objectAtIndex:i]);
            UIImage *img=[[UIImage alloc] initWithContentsOfFile:[arr objectAtIndex:i]];
            pbModel.image=img;
            
            //源frame
            //UIImageView *imageV =(UIImageView *) weakSelf.contentView.subviews[i];
            pbModel.sourceImageView = imgView; // imageV;
            
            [modelsM addObject:pbModel];
        }
        
        return modelsM;
    }];
}
#pragma mark UISwitch
-(void)switchAction:(id)sender
{
    
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    NSDictionary* dict=[arrList objectAtIndex:iindex];
    
    SetMailReadFlagRequest * request = [[SetMailReadFlagRequest alloc] init];
    request.token = token;
    request.msgids=@[[dict objectForKey:@"msgid"]];
    
    UISwitch* switch1=(UISwitch*)sender;
    
//    NSIndexPath *indexPath = 0;
//    UITableViewCell *cell = [mailTableView cellForRowAtIndexPath:indexPath];
//    UILabel* lab4=(UILabel*)[cell viewWithTag:14];
    if (switch1.on)
    {
//        lab4.text=@"已读";
        request.read_flag=1;
        icount=1;
    }
    else {
//        lab4.text=@"未读";
        icount=2;
        request.read_flag=0;
    }
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[SetMailReadFlagResponse class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    SetMailReadFlagResponse* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
        [self showAlertWithContent:rslt.ErrMsg];
    }
    else{
        [mailTableView reloadData];
    
        //[btnOk setTitle:@"未确认" forState:UIControlStateNormal];
    }
}];
//    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *plistPath = [rootPath stringByAppendingPathComponent:@"wifiData.plist"];
//    
//    UISwitch *switchButton = (UISwitch*)sender;
//    BOOL isButtonOn = [switchButton isOn];
//    if (isButtonOn) {
//        NSDictionary *dictionary = @{@"wifi":@"ON"};
//        [dictionary writeToFile:plistPath atomically:YES];
//    }else {
//        NSDictionary *dictionary = @{@"wifi":@"OFF"};
//        [dictionary writeToFile:plistPath atomically:YES];
//    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)loadContent:(NSString*)strcon withWeb:(UIWebView*)webView {
    NSString *path1 = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path1];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"html"];
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSString *str = [[NSString alloc] initWithData:
                     [readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
    
    int fontsize = 14;
    int lineHeight = fontsize;
    
    str = [str stringByReplacingOccurrencesOfString:@"{FONT_SIZE}" withString:[NSString stringWithFormat:@"%d",fontsize]];
    str = [str stringByReplacingOccurrencesOfString:@"{LINE_HEIGHT}" withString:[NSString stringWithFormat:@"%d",lineHeight]];
    
    NSString *contentString = strcon;
    NSRange r;
    while ((r = [contentString rangeOfString:@"style=\"[^p][^>]*\\/?[^p]\"" options:NSRegularExpressionSearch]).location != NSNotFound)
        contentString = [contentString stringByReplacingCharactersInRange:r withString:@""];
    while ((r = [contentString rangeOfString:@"width=\"[^\"]*\"" options:NSRegularExpressionSearch]).location != NSNotFound)
        contentString = [contentString stringByReplacingCharactersInRange:r withString:@""];
    while ((r = [contentString rangeOfString:@"height=\"[^\"]*\"" options:NSRegularExpressionSearch]).location != NSNotFound)
        contentString = [contentString stringByReplacingCharactersInRange:r withString:@""];
    
    str = [str stringByReplacingOccurrencesOfString:@"{title}" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"{content}" withString:contentString];
    
    [webView loadHTMLString:str baseURL:baseURL];
}
@end
